package model

import (
	"ginblog/utils/errmsg"

	"gorm.io/gorm"
)

// Article 文章存储表
type Article struct {
	Category Category `gorm:"foreignKey:Cid"` // 自定义外键 Cid
	gorm.Model
	Title   string `gorm:"type:varchar(100);not null" json:"title"`
	Cid     int    `gorm:"type:int;not null" json:"cid"`
	Desc    string `gorm:"type:varchar(200)" json:"desc"`
	Content string `gorm:"type:longtext" json:"content"`
	Img     string `gorm:"type:varchar(100)" json:"img"`
}

// CreateArticle 新增文章
func CreateArticle(data *Article) (code int) {
	err := db.Create(&data).Error
	if err != nil {
		return errmsg.ERROR // 500
	}
	return errmsg.SUCCESS
}

// GetArticlesOfCategory 查询分类下的所有文章
func GetArticlesOfCategory(cid int, pageSize int, pageNum int) ([]Article, int, int64) {
	var cataArticleList []Article
	var total int64
	err = db.Preload("Category").Limit(pageSize).Offset((pageNum-1)*pageSize).Where("cid = ?", cid).Find(&cataArticleList).Count(&total).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errmsg.ERROR, 0
	}
	return cataArticleList, errmsg.SUCCESS, total
}

// GetArticleInfo 查询单个文章
func GetArticleInfo(id int) (Article, int) {
	var article Article
	err := db.Preload("Category").Where("id = ?", id).First(&article).Error
	if err != nil {
		return article, errmsg.ERROR_ARTICLE_NOT_EXIST
	}
	return article, errmsg.SUCCESS
}

// GetArticles 查询文章列表
func GetArticles(title string, pageSize int, pageNum int) ([]Article, int, int64) {
	var articleList []Article
	var total int64
	if title == "" {
		err = db.Preload("Category").Find(&articleList).Count(&total).Limit(pageSize).Offset((pageNum - 1) * pageSize).Error
		if err != nil && err != gorm.ErrRecordNotFound {
			return nil, errmsg.ERROR_CATEGORY_NOT_EXITS, 0
		}
		return articleList, errmsg.SUCCESS, total
	}
	err = db.Preload("Category").Where("title LIKE ?", "%"+title+"%").Find(&articleList).Count(&total).Limit(pageSize).Offset((pageNum - 1) * pageSize).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errmsg.ERROR_CATEGORY_NOT_EXITS, 0
	}
	return articleList, errmsg.SUCCESS, total
}

// EditArticle 编辑文章信息 只可修改密码以外的字段
func EditArticle(id int, data *Article) int {
	var cate Article

	var maps = make(map[string]interface{})
	maps["title"] = data.Title
	maps["cid"] = data.Cid
	maps["desc"] = data.Desc
	maps["content"] = data.Content
	maps["img"] = data.Img

	err = db.Model(&cate).Where("id = ?", id).Updates(maps).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

// DeleteArticle 删除文章的方法
func DeleteArticle(id int) int {
	err = db.Where("id = ?", id).Delete(&Article{}).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}
